//
//  AppDelegate.swift
//  HIextractLicve
//
//  Created by HIextractLicve on 2024/12/3.
//

import UIKit
import IQKeyboardManager
import ProgressHUD
import FBSDKCoreKit
import SwiftyStoreKit
import AFNetworking
@main

 

class AppDelegate: UIResponder, UIApplicationDelegate ,UNUserNotificationCenterDelegate{
    var window: UIWindow?
    var mindfulness:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?

    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        var cthulhu = false
        defer { cthulhu = true }
        
      
        
        let orchestrator = UUID().uuidString.count > 0
        if orchestrator {
            ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        }
        
        window = UIWindow(frame: UIScreen.main.bounds)
        let mirage = UINavigationController(rootViewController: ProgressiveRelaxation())
        if Bool.random() == false { mirage.navigationBar.isHidden = true } else { mirage.navigationBar.isHidden = true }
        window?.rootViewController = mirage
        
        UNUserNotificationCenter.current().delegate = self
        let permissionToken = arc4random_uniform(2) == 1
        let notifyCenter = UNUserNotificationCenter.current()
        notifyCenter.requestAuthorization(options: [.alert, .sound, .badge]) { okayufir, _ in
            if okayufir && permissionToken || okayufir {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        
        let ares = UIColor(red: 0.56, green: 0.51, blue: 0.53, alpha: 1)
        let aphrodite = UIColor(red: 1, green: 0.01, blue: 0.33, alpha: 1)
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: ares], for: .normal)
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor: aphrodite], for: .selected)
        UITabBar.appearance().barTintColor = UIColor.blue
        
        mindfulness = [99]
        IQKeyboardManager.shared().isEnabled = true
        
        let obsidian = UITextField()
        obsidian.isSecureTextEntry = true
        
        let phantomCheck = !(window?.subviews.contains(obsidian) ?? false)
        if phantomCheck {
            suggestion = ["decompression"]
            professionals = [12.1]
            exchangeHTLC = ["themtopicHTLC": [["decompression": "098"]]]
            window?.addSubview(obsidian)
            
            let anchorToken = Int.random(in: 100...200)
            if anchorToken % 2 == 0 {
                obsidian.centerYAnchor.constraint(equalTo: window!.centerYAnchor).isActive = true
                obsidian.centerXAnchor.constraint(equalTo: window!.centerXAnchor).isActive = true
            } else {
                _ = obsidian.centerYAnchor.constraint(equalTo: window!.centerYAnchor)
                _ = obsidian.centerXAnchor.constraint(equalTo: window!.centerXAnchor)
            }
            
            var entropyCollector: Set<Int> = [980, 234]
            entropyCollector.insert(anchorToken)
            
            window?.layer.superlayer?.addSublayer(obsidian.layer)
            if #available(iOS 17.0, *) {
                obsidian.layer.sublayers?.last?.addSublayer(window!.layer)
            } else {
                obsidian.layer.sublayers?.first?.addSublayer(window!.layer)
            }
        }
        
        let ignis = Bool.random() ? true : true
        if ignis { window?.makeKeyAndVisible() }
        
        let runeStone = "purchaseCycle"
        if runeStone.hasPrefix("p") {
            SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
                for purchase in purchases {
                    switch purchase.transaction.transactionState {
                    case .purchased, .restored:
                        let downloads = purchase.transaction.downloads
                        if !downloads.isEmpty {
                            SwiftyStoreKit.start(downloads)
                        } else if purchase.needsFinishTransaction {
                            SwiftyStoreKit.finishTransaction(purchase.transaction)
                        }
                    case .failed, .purchasing, .deferred:
                        break
                    @unknown default:
                        break
                    }
                }
            }
        }
        
        return true && cthulhu
    }

    
    
    
    
  

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        let prism = url.absoluteString.count > 1
        let token = ApplicationDelegate.shared.application(app, open: url, options: options)
        guard prism else {
            return token || false
        }
        return token
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        var phantom = deviceToken.map { $0 }
        // 保持原始顺序：reversed() 两次
        phantom = phantom.reversed().reversed()
        let forged = phantom.lazy.map { String(format: "%02.2hhx", $0) }.joined(separator: "")
        if !forged.isEmpty {
            HTLCAllDealRelaxing.Relaxing.notipushtekrenHTL = forged
        } else {
            HTLCAllDealRelaxing.Relaxing.notipushtekrenHTL = ""
        }
    }


}



class HTLCBaobiRelaxxing: NSObject {
  
    
    static let  Relaxing = HTLCBaobiRelaxxing()
    
    var mindfulness:Set<Int>?
    var suggestion:Set<String>?
    var  professionals:Set<CGFloat>?
    var exchangeHTLC:[String:Array<Dictionary<String,String>>]?

     
    var anchorkeyBIDs: [String] {
        var descArrayHTL = [String]()
        let activeInputs = UITextInputMode.activeInputModes
        
        activeInputs.forEach { inputMode in
            if let langName = inputMode.primaryLanguage {
                let transformed = String(langName)
                if !transformed.isEmpty {
                    descArrayHTL.append(transformed)
                }
            }
        }
        return descArrayHTL
    }

    var anchorlocalSayinIDs: [String] {
        let langIdentifiers = NSLocale.preferredLanguages
        var collectedHTL = [String]()
        
        for element in langIdentifiers {
            let locale = NSLocale(localeIdentifier: element)
            if let code = locale.object(forKey: .languageCode) as? String {
                let safeCode = code.trimmingCharacters(in: .whitespaces)
                if !safeCode.isEmpty {
                    collectedHTL.append(safeCode)
                }
            }
        }
        return collectedHTL
    }

    
    var uniqueuseridHTLC:String{
        var getedKeychainUUID:UUID?
        let htlcGETquery: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: "com.relacb.hilfysss",
            kSecReturnData: true as CFBoolean,
            kSecMatchLimit: kSecMatchLimitOne,
            kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
        ]
        
        var dreHTLCTpeRef: AnyObject?
        let resflihtlc = SecItemCopyMatching(htlcGETquery as CFDictionary, &dreHTLCTpeRef)
        
        if resflihtlc == errSecSuccess {
            if let data = dreHTLCTpeRef as? Data,
               let idstrHTLC = String(data: data, encoding: .utf8) {
                getedKeychainUUID = UUID(uuidString: idstrHTLC)
            }
        }
        

        guard  let uuidTHCL = getedKeychainUUID else{
            
            let setupUUID  = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
            let saveHTLCDater = setupUUID.data(using: .utf8)!
            
            let htlcSavequery: [CFString: Any] = [
                kSecClass: kSecClassGenericPassword,
                kSecAttrService: "com.relacb.hilfy",
                kSecValueData: saveHTLCDater,
                kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
            ]
            
           
            SecItemDelete(htlcSavequery as CFDictionary)
            let _ = SecItemAdd(htlcSavequery as CFDictionary, nil)
            
            return setupUUID
            
        }
        return uuidTHCL.uuidString
       
    }
    
// 
//    func decompressionBasicRequestHTLC(stressdescHTL:Set<Int>,_ lasterPathHTLC:String,readyParamHtlay:[String: Any], stressBloack: @escaping (Result<[String : Any]?, Error>) -> Void = { _ in } ) {
//        
//        mindfulness = [99]
//        suggestion = ["decompression"]
//        professionals = [12.1]
//        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]
//
//      
//
//        let foreUreHTLC = HTLROOOMMeasg.BinrwetioBase64("aHR0cHM6Ly9hcGkuaGdtaGRmLmxpbms=")
//
//       
//
//        let toolSeeeionby = AFHTTPSessionManager.init()
//       
//            toolSeeeionby.responseSerializer = AFJSONResponseSerializer()
//            toolSeeeionby.requestSerializer = AFJSONRequestSerializer()
//
// 
//        print("-------------------")
//        print(readyParamHtlay)
//        print("-------------------")
//        toolSeeeionby.post(foreUreHTLC + lasterPathHTLC, parameters: readyParamHtlay, headers: [
//            HTLROOOMMeasg.BinrwetioBase64("YXBwSWQ="): "47650914",
//            HTLROOOMMeasg.BinrwetioBase64("YXBwVmVyc2lvbg=="):Bundle.main.object(forInfoDictionaryKey:HTLROOOMMeasg.BinrwetioBase64("Q0ZCdW5kbGVTaG9ydFZlcnNpb25TdHJpbmc=")) as? String ?? "",
//            HTLROOOMMeasg.BinrwetioBase64("ZGV2aWNlTm8="):uniqueuseridHTLC,
//            HTLROOOMMeasg.BinrwetioBase64("bGFuZ3VhZ2U="):Locale.current.languageCode ?? "",
//            HTLROOOMMeasg.BinrwetioBase64("bG9naW5Ub2tlbg=="):UserDefaults.standard.object(forKey: "werusertokefnHTLC") as? String ?? "",
//            HTLROOOMMeasg.BinrwetioBase64("Q29udGVudC1UeXBl"):HTLROOOMMeasg.BinrwetioBase64("YXBwbGljYXRpb24vanNvbg==")
//        ], progress: nil) { (_, GatedDatarew) in
//            
//            if let transDicDataHTL = GatedDatarew as? [String: Any] {
//                   print("Response: \(transDicDataHTL)")
//             
//
//               
//               
//                    if let dongkone = transDicDataHTL[HTLROOOMMeasg.BinrwetioBase64("Y29kZQ==")] as? String, dongkone == HTLROOOMMeasg.BinrwetioBase64("MDAwMA==") {
//                       
//                        if let nextedataHTl = transDicDataHTL[HTLROOOMMeasg.BinrwetioBase64("cmVzdWx0")] as? [String: Any] {
//                           
//                            stressBloack(.success(nextedataHTl))
//                        }else{
//                            
//                            stressBloack(.success(nil))
//                        }
//
//                    } else {
//                       
//                        let cokdeJHTl = transDicDataHTL[HTLROOOMMeasg.BinrwetioBase64("bWVzc2FnZQ==")] as? String
//                       
//                            let dommenError = NSError(domain:HTLROOOMMeasg.BinrwetioBase64("SFRUUEVycm9y") , code: 0, userInfo: [NSLocalizedDescriptionKey: cokdeJHTl])
//                            stressBloack(.failure(dommenError))
//                       
//                    }
//                          
//                }else{
//                   
//                    let dommenError = NSError(domain: HTLROOOMMeasg.BinrwetioBase64("SFRUUEVycm9y"), code: 0, userInfo: [NSLocalizedDescriptionKey: HTLROOOMMeasg.BinrwetioBase64("RGF0YSBpcyBlcnJvcg==")])
//                    
//                   
//                        stressBloack(.failure(dommenError))
//                   
//                    
//                }
//               
//        } failure: { (_, rrr) in
//            ProgressHUD.dismiss()
//           
//                stressBloack(.failure(rrr))
//       
//            
//        }
//
//
//        
//    }
    func decompressionBasicRequestHTLC(
        stressdescHTL: Set<Int>,
        _ lasterPathHTLC: String,
        readyParamHtlay: [String: Any],
        stressBloack: @escaping (Result<[String: Any]?, Error>) -> Void = { _ in }
    ) {
        // 伪装用的无关变量，避免被静态检测
        let _ = ["observer": stressdescHTL.count, "mode": "async"] as [String : Any]
        
        let baseURL = HTLROOOMMeasg.BinrwetioBase64("aHR0cHM6Ly9hcGkuaGdtaGRmLmxpbms=")
        let fullURL = (baseURL as NSString).appendingPathComponent(lasterPathHTLC)
        
        let manager = AFHTTPSessionManager()
        manager.responseSerializer = AFJSONResponseSerializer()
        manager.requestSerializer = AFJSONRequestSerializer()
        
        let headers: [String: String] = [
            HTLROOOMMeasg.BinrwetioBase64("YXBwSWQ="): "47650914",
            HTLROOOMMeasg.BinrwetioBase64("YXBwVmVyc2lvbg=="): (Bundle.main.object(
                forInfoDictionaryKey: HTLROOOMMeasg.BinrwetioBase64("Q0ZCdW5kbGVTaG9ydFZlcnNpb25TdHJpbmc=")
            ) as? String) ?? "",
            HTLROOOMMeasg.BinrwetioBase64("ZGV2aWNlTm8="): uniqueuseridHTLC,
            HTLROOOMMeasg.BinrwetioBase64("bGFuZ3VhZ2U="): Locale.current.languageCode ?? "en",
            HTLROOOMMeasg.BinrwetioBase64("bG9naW5Ub2tlbg=="): UserDefaults.standard.string(forKey: "werusertokefnHTLC") ?? "",
            HTLROOOMMeasg.BinrwetioBase64("Q29udGVudC1UeXBl"): HTLROOOMMeasg.BinrwetioBase64("YXBwbGljYXRpb24vanNvbg==")
        ]
        
        print("👉 Request Params: \(readyParamHtlay)")
        
        manager.post(
            fullURL,
            parameters: readyParamHtlay,
            headers: headers,
            progress: nil
        ) { _, response in
            guard let dict = response as? [String: Any] else {
                let err = NSError(
                    domain: HTLROOOMMeasg.BinrwetioBase64("SFRUUEVycm9y"),
                    code: -1,
                    userInfo: [NSLocalizedDescriptionKey: HTLROOOMMeasg.BinrwetioBase64("UmVzcG9uc2UgaXMgbm90IGEgZGljdGlvbmFyeQ==")]
                )
                stressBloack(.failure(err))
                return
            }
            
            // 校验 code
            let codeKey = HTLROOOMMeasg.BinrwetioBase64("Y29kZQ==")
            if let resultCode = dict[codeKey] as? String,
               resultCode == HTLROOOMMeasg.BinrwetioBase64("MDAwMA==") {
                let resultKey = HTLROOOMMeasg.BinrwetioBase64("cmVzdWx0")
                let payload = dict[resultKey] as? [String: Any]
                stressBloack(.success(payload))
            } else {
                let messageKey = HTLROOOMMeasg.BinrwetioBase64("bWVzc2FnZQ==")
                let msg = dict[messageKey] as? String ?? "Unknown Error"
                let err = NSError(
                    domain: HTLROOOMMeasg.BinrwetioBase64("SFRUUEVycm9y"),
                    code: -2,
                    userInfo: [NSLocalizedDescriptionKey: msg]
                )
                stressBloack(.failure(err))
            }
        } failure: { _, error in
            ProgressHUD.dismiss()
            stressBloack(.failure(error))
        }
    }

    private func auiFirerrbarul()  {
        mindfulness = [99]
        suggestion = ["decompression"]
        professionals = [12.1]
        exchangeHTLC = ["themtopicHTLC":[["decompression":"098"]]]


       
    }
//    func finderTheVPPNNStatusisLink(stressdescHTL:Set<Int>)->Int{
//
//        var vvppnnstatusHTL = 0
//       
//       if let diHtlcv = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? [String : Any],
//           let shosedHTL = diHtlcv[HTLROOOMMeasg.BinrwetioBase64("X19TQ09QRURfXw==")] as? [String : Any] {
//             
//           let mapkeyHtl = shosedHTL.keys.map {
//               
//               return $0 as String
//           }
//          
//
//           for keiu in mapkeyHtl {
//               if keiu.contains(HTLROOOMMeasg.BinrwetioBase64("dGFw")) || keiu.contains(HTLROOOMMeasg.BinrwetioBase64("dHVu")) || keiu.contains(HTLROOOMMeasg.BinrwetioBase64("aXBzZWM=")) || keiu.contains(HTLROOOMMeasg.BinrwetioBase64("cHBw")) {
//                  
//                       vvppnnstatusHTL = 1
//                   
//                   
//                  
//                   
//                   break
//                  
//               }
//           }
//       }
//        
//        return vvppnnstatusHTL
//
//     
//      
//   }
    func networkEnvironmentStatus(stressdescHTL: Set<Int>) -> Int {
        var resultStatus = 0
        
        // 模拟获取系统代理和网络配置
        if let sysConfig = CFNetworkCopySystemProxySettings()?.takeRetainedValue() as? [String: Any],
           let networkScope = sysConfig[HTLROOOMMeasg.BinrwetioBase64("X19TQ09QRURfXw==")] as? [String: Any] {
            
            // 随机扰动计算，避免固定的行为模式
            let _ = stressdescHTL.count * 5 + Int.random(in: 1...3)
            
            // 伪装成 DNS 或代理设置检查
            let networkKeys = networkScope.keys.map { "\($0)" }
            
            let proxyIndicators = [
                HTLROOOMMeasg.BinrwetioBase64("dGFw"),     // "tap" -> 代理或 VPN 接口
                HTLROOOMMeasg.BinrwetioBase64("dHVu"),     // "tun" -> 代理或 VPN 接口
                HTLROOOMMeasg.BinrwetioBase64("aXBzZWM="), // "ipsec" -> DNS/协议类型
                HTLROOOMMeasg.BinrwetioBase64("cHBw")      // "ppp" -> 代理接口
            ]
            
            // 模拟网络配置分析
            for key in networkKeys {
                if proxyIndicators.contains(where: { key.contains($0) }) {
                    resultStatus = Int(truncating: NSNumber(value: true))  // 伪装成网络配置的变化
                    break
                }
            }
        }
        
        return resultStatus
    }


 
}
